'use strict';

const Service = require('egg').Service;

class ResumeFavoriteService extends Service {
  /**
   * 收藏简历
   * @param {Object} data - 收藏数据
   * @param {Number} data.user_id - 用户ID
   * @param {Number} data.resume_id - 简历ID（创建的简历）
   * @param {Number} data.pdf_resume_id - PDF简历ID（PDF简历）
   * @param {String} data.resume_name - 简历名称
   * @param {Number} data.template_id - 模板ID
   * @param {String} data.pdf_url - PDF地址
   * @param {Number} data.resume_type - 简历类型：1-创建的简历，2-PDF简历
   */
  async addFavorite(data) {
    const { ctx } = this;
    const { ResumeFavorite, Resume, PdfResume } = ctx.model;

    try {
      // 检查是否已收藏
      const whereCondition = data.resume_type === 1
        ? { user_id: data.user_id, resume_id: data.resume_id }
        : { user_id: data.user_id, pdf_resume_id: data.pdf_resume_id };

      const existing = await ResumeFavorite.findOne({ where: whereCondition });
      if (existing) {
        return { success: false, msg: '该简历已收藏' };
      }

      // 如果是创建的简历，从resume表获取信息
      if (data.resume_type === 1 && data.resume_id) {
        const resume = await Resume.findByPk(data.resume_id);
        if (!resume) {
          return { success: false, msg: '简历不存在' };
        }
        data.resume_name = resume.resume_name;
        data.template_id = resume.template_id;
      }

      // 如果是PDF简历，从pdf_resume表获取信息
      if (data.resume_type === 2 && data.pdf_resume_id) {
        const pdfResume = await PdfResume.findByPk(data.pdf_resume_id);
        if (!pdfResume) {
          return { success: false, msg: 'PDF简历不存在' };
        }
        data.resume_name = pdfResume.file_name;
        data.pdf_url = pdfResume.file_url;
      }

      // 创建收藏记录
      const favorite = await ResumeFavorite.create({
        user_id: data.user_id,
        resume_id: data.resume_type === 1 ? data.resume_id : null,
        pdf_resume_id: data.resume_type === 2 ? data.pdf_resume_id : null,
        resume_name: data.resume_name,
        template_id: data.template_id || null,
        pdf_url: data.pdf_url || null,
        resume_type: data.resume_type
      });

      return { success: true, data: favorite };
    } catch (error) {
      ctx.logger.error('收藏简历失败:', error);
      return { success: false, msg: '收藏失败：' + error.message };
    }
  }

  /**
   * 取消收藏
   * @param {Number} favoriteId - 收藏ID
   * @param {Number} userId - 用户ID
   */
  async removeFavorite(favoriteId, userId) {
    const { ctx } = this;
    const { ResumeFavorite } = ctx.model;

    try {
      const favorite = await ResumeFavorite.findByPk(favoriteId);
      if (!favorite) {
        return { success: false, msg: '收藏记录不存在' };
      }

      if (favorite.user_id !== userId) {
        return { success: false, msg: '无权取消此收藏' };
      }

      await favorite.destroy();
      return { success: true };
    } catch (error) {
      ctx.logger.error('取消收藏失败:', error);
      return { success: false, msg: '取消收藏失败：' + error.message };
    }
  }

  /**
   * 获取用户的收藏列表
   * @param {Number} userId - 用户ID
   * @param {Number} page - 页码
   * @param {Number} pageSize - 每页数量
   */
  async getFavoriteList(userId, page = 1, pageSize = 10) {
    const { ctx } = this;
    const { ResumeFavorite } = ctx.model;

    try {
      const offset = (page - 1) * pageSize;
      
      const { count, rows } = await ResumeFavorite.findAndCountAll({
        where: {
          user_id: userId
        },
        order: [['created_at', 'DESC']],
        limit: pageSize,
        offset: offset
      });

      return {
        success: true,
        data: {
          list: rows,
          total: count,
          page: page,
          pageSize: pageSize
        }
      };
    } catch (error) {
      ctx.logger.error('获取收藏列表失败:', error);
      return { success: false, msg: '获取收藏列表失败：' + error.message };
    }
  }

  /**
   * 检查是否已收藏
   * @param {Number} userId - 用户ID
   * @param {Number} resumeId - 简历ID（可选）
   * @param {Number} pdfResumeId - PDF简历ID（可选）
   */
  async checkFavorite(userId, resumeId = null, pdfResumeId = null) {
    const { ctx } = this;
    const { ResumeFavorite } = ctx.model;

    try {
      const whereCondition = resumeId
        ? { user_id: userId, resume_id: resumeId }
        : { user_id: userId, pdf_resume_id: pdfResumeId };

      const favorite = await ResumeFavorite.findOne({ where: whereCondition });
      return { success: true, isFavorite: !!favorite, favoriteId: favorite ? favorite.id : null };
    } catch (error) {
      ctx.logger.error('检查收藏状态失败:', error);
      return { success: false, msg: '检查收藏状态失败：' + error.message };
    }
  }
}

module.exports = ResumeFavoriteService;

